package com.gree.changying.activity.mainactivity.framgent.homefrm.tuijian.adapter;


import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by 游德禄 on 2019-11-6
 */
public class ViewPagerAdapter extends PagerAdapter {
    private List<View> viewList = new ArrayList<>();

    public ViewPagerAdapter(){
    }

    public void update(List<View> views){
        this.viewList = new ArrayList<>(views);
        notifyDataSetChanged();
    }
    /**
     * 添加
     * @param view
     */
    public void add(View view){
        this.viewList.add(view);
        notifyDataSetChanged();
    }

    /**
     * 删除
     * @param position
     */
    public void remove(int position){
        this.viewList.remove(getView(position));
        notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        //让viewpager每次都更新
        return POSITION_NONE;
    }

    public View getView(int position){
        return viewList.get(position);
    }

    public void clear(){
        this.viewList.clear();
        this.viewList = new ArrayList<>();
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return viewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(viewList.get(position));
        return viewList.get(position);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        if(position<viewList.size()) {
            container.removeView(viewList.get(position));
        }
        container.removeView((View)object);
    }
}
